package cn.pconline.autoclub.web;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubForum;
import cn.pconline.autoclub.entity.Topic;
import cn.pconline.autoclub.entity.TopicImage;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.TopicService;
import cn.pconline.autoclub.util.AppUtils;
import cn.pconline.autoclub.util.Bread;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.WebUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 帖子相关controller
 */
@Controller
public class TopicController {

    private final static int DEFAULT_PAGE_SIZE = 20;
    private final static int MAX_PAGE_SIZE = 100;
    private final static int MIN_PAGE_SIZE = 1;
    @Autowired
    private TopicService topicService;
    @Autowired
    private UserAuth userAuth;
    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private ClubService clubService;
    
    protected static final Logger log = LoggerFactory.getLogger(TopicController.class);

     /**
     * 发帖
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/topic/post.do", method = RequestMethod.GET)
    public String post(HttpServletRequest request, HttpServletResponse response) {
    	long clubId = WebUtils.paramLong(request, "clubId", 0L);
    	Club club = clubService.getValidClub(clubId);
        if (club == null) {
            try {
            	response.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("error", ex);
            }
        }
        ClubForum forum = clubService.getDefaultForum( clubId );
        if(forum==null){
        	try {
            	response.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("error", ex);
            }
        }
        ClubController.setClubStyle(request, club.getClubId());
        request.setAttribute("club", club);
        request.setAttribute("fId", forum.getForumId());
        String type = request.getParameter("type");
        request.setAttribute("type", type);
        request.setAttribute("returnUrl", systemConfig.getRoot()+"/"+club.getClubUrl()+"/topic/");
        return "/template/topic/post";
    }
    
    
    /**
     * 帖子列表页
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/topic/topics", method = RequestMethod.GET)
    public String topics(HttpServletRequest request, HttpServletResponse response) {
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        int pageSize = WebUtils.paramInt(request, "pageSize", DEFAULT_PAGE_SIZE, 1, MAX_PAGE_SIZE);
        long clubId = WebUtils.paramLong(request, "clubId", 0L);
        int type = WebUtils.paramInt(request, "type", 1); //1》全部，2》精华帖
        Club club = clubService.getValidClub(clubId);
        if (club == null || pageNo <1) {
            try {
                response.sendError(404);
            } catch (Exception ex) {
                log.error("topics fail!", ex);
            }
            return "/template/club/notFoundPage";
        }

        Pager<Topic> pager = topicService.getTopicsWithUsers(type,clubId, pageNo, pageSize);
        WebUtils.checkPageMaxNo(response,pageNo,pager.getPageCount());
        request.setAttribute("clubId", clubId);
        request.setAttribute("pager", pager);
        request.setAttribute("club", club);
        request.setAttribute("user", userAuth.getUser(request, response));
        
        List<Bread> breadList = new ArrayList<Bread>(2);
        String retUrl = "/template/topic/topic_list";
        if(type==2){
        	breadList.add(new Bread(systemConfig.getRoot() + "/" + request.getParameter("desc") + "/best/", "精华帖子"));
        	retUrl = "/template/topic/pick_list";
        }else{
        	breadList.add(new Bread(systemConfig.getRoot() + "/" + request.getParameter("desc") + "/topic/", "全部帖子"));
        }
        request.setAttribute("breadList", breadList);
        request.setAttribute("club", club);
        return retUrl;
    }
    /**
     * 
     * 车友会动态接口 【APP】
     * @throws IOException 
     */
    @ResponseBody
    @RequestMapping(value = "/topic/listTopicByClubId.do" , method = RequestMethod.GET)
    public void listTopicByClubId(HttpServletRequest req, HttpServletResponse resp) throws IOException{
    	WebUtils.setEncoding(req, resp);
    	String callback = WebUtils.param(req, "callback", "");
    	long clubId = WebUtils.paramLong(req, "clubId", 0);
        int IMAGES_TYPE_NEW = 1;//新APP接口 imageType默认为0，表示旧APP接口
    	int imagesType = WebUtils.paramInt(req, "imagesType", 0);
    	int pageSize = WebUtils.paramInt(req, "pageSize", 20,MIN_PAGE_SIZE,MAX_PAGE_SIZE);
    	int pageNo = WebUtils.paramInt(req, "pageNo", 1);
    	int sourceAgent = WebUtils.paramInt(req, "source_agent", 2);
    	JSONObject json = new JSONObject();
    	json.put("clubId", clubId);
    	Club club = clubService.getValidClub(clubId);
    	if(club!=null){
    		JSONArray jsonArray = new JSONArray();
    		Pager<Topic> pager = topicService.getTopicsWithUsers(1,clubId, pageNo, pageSize);
    		if(pager.getResultList()!= null && !pager.getResultList().isEmpty()){
    			for(Topic topic : pager.getResultList()){
    				JSONObject jsonObject = new JSONObject();
    				jsonObject.put("authorId", topic.getTopicAuthor().getUid());
    				jsonObject.put("authorName", EncodeUtils.encodeForHTML(topic.getTopicAuthor().getUsername(),sourceAgent));
    				jsonObject.put("nickname", EncodeUtils.encodeForHTML(topic.getTopicAuthor().getNickname(),sourceAgent));
    				jsonObject.put("authorPhoto", WebUtils.face(topic.getTopicAuthor().getUid(), 50));
    				jsonObject.put("forumId", topic.getForumId());
    				jsonObject.put("forumName", EncodeUtils.encodeForHTML(topic.getForumName(),sourceAgent));
    				jsonObject.put("topicId", topic.getTopicId());
    				jsonObject.put("topicTitle", EncodeUtils.encodeForHTML(topic.getTopicTitle(),sourceAgent));
    				jsonObject.put("message", EncodeUtils.encodeForHTML(topic.getMessage(),sourceAgent));
    				if(imagesType==IMAGES_TYPE_NEW){
                                    JSONArray imgs = new JSONArray();
                                    List<TopicImage> images = topicService.getImagesByTopicId(topic.getTopicId(),TopicImage.MAX_IMAGE);
                                    for(TopicImage t:images){
                                        if(StringUtils.isBlank(t.getUrl())){
                                            continue;
                                        }
                                        JSONObject o = new JSONObject();
                                        o.put("url", t.getUrl());
                                        o.put("width", t.getWidth());
                                        o.put("height", t.getHeight());
                                        if(t.getWidth()>0 && t.getHeight()>0){
                                            imgs.add(o);
                                        }
                                    }
                                    jsonObject.put("images", imgs);
                                }else{
                                    jsonObject.put("image1", topic.getAppImage1());
                                    jsonObject.put("image2", topic.getAppImage2());
                                    jsonObject.put("image3", topic.getAppImage3());
    				}
                                jsonObject.put("isHasImg", (StringUtils.isNotBlank(topic.getImage1())||
    						StringUtils.isNotBlank(topic.getImage2())||StringUtils.isNotBlank(topic.getImage3())));
    				jsonObject.put("isPick", (topic.getPick()==1||topic.getPick()==2));
    				jsonObject.put("isRecommend", (topic.getRecommend()==1));
    				jsonObject.put("pubTime", topic.getCreateAt().getTime());
    				jsonObject.put("contribution", topic.getPetrol());
    				jsonObject.put("postCount", topic.getPostCount());
    				jsonArray.add(jsonObject);
    			}
                        AppUtils.setSuccessCode(json);
    			json.put("data", jsonArray);
    			json.put("total", pager.getTotal());
    			json.put("pageNo", pager.getPageNo());
    			json.put("pageSize", pager.getPageSize());
    		}
    	}else{
                AppUtils.setDataErrorCode(json, "该车友会ID不存在");
    	}
    	
        if (StringUtils.isBlank(callback)) {
        	resp.getWriter().println(json.toString());
    	} else{
    		resp.getWriter().println(EncodeUtils.encodeForHTMLFilterNull(callback) + "(" + json.toString() + ")");
    	}
    }
    
    /**
     * 帖子列表页(wap)
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/wap/topic/topics", method = RequestMethod.GET)
    public String topicPage(HttpServletRequest request, HttpServletResponse response) {
        long clubId = WebUtils.paramLong(request, "clubId", 0L);
        Club club = clubService.getValidClub(clubId);
        if (club == null) {
        	return "redirect:http://m.pcauto.com.cn/x/404/";
        }
        request.setAttribute("club", club);
        request.setAttribute("user", userAuth.getUser(request, response));
    	
        return "/template/wap/topic/topic_list";
    }
    
    /**
     * 车友会动态接口(wap)
     * @throws IOException 
     */
    @ResponseBody
    @RequestMapping(value = "/wap/listTopicByClubId.do" , method = RequestMethod.GET)
    public void listsTopicByClubId(HttpServletRequest req, HttpServletResponse resp) 
    		throws IOException{
    	WebUtils.setEncoding(req, resp);
    	String callback = WebUtils.param(req, "callback", "");
    	long clubId = WebUtils.paramLong(req, "clubId", 0);
    	int pageSize = WebUtils.paramInt(req, "pageSize", 5);
    	int pageNo = WebUtils.paramInt(req, "pageNo", 1);
    	int sourceAgent = WebUtils.paramInt(req, "source_agent", 2);
    	req.setAttribute("pageNo", pageNo);
    	req.setAttribute("pageSize", pageSize);
        
    	JSONObject json = new JSONObject();
    	Pager<Topic> pager = topicService.getTopicsWithUsers(1,clubId, pageNo, pageSize);
    	if(pager != null){
    		JSONArray jsonArray = new JSONArray();
    		if(pager.getResultList()!= null && !pager.getResultList().isEmpty()){
    			for(Topic topic : pager.getResultList()){
    				JSONObject jsonObject = new JSONObject();
    				jsonObject.put("topicTitle", (EncodeUtils.encodeForHTML(topic.getTopicTitle(),sourceAgent)));
    				jsonObject.put("topicAuthor", (EncodeUtils.encodeForHTML(topic.getTopicAuthor().getNickname(),sourceAgent)));
    				jsonObject.put("topicPick", topic.getPick());
    				jsonObject.put("topicId", topic.getTopicId());
    				jsonObject.put("image1", topic.getImage1());
    				jsonObject.put("image2", topic.getImage2());
    				jsonObject.put("image3", topic.getImage3());
    				jsonObject.put("recommend", topic.getRecommend());
    				jsonObject.put("createAt", DateUtils.formatYYMMDDHM(topic.getCreateAt()));
    				jsonObject.put("petrol", topic.getPetrol());
    				jsonArray.add(jsonObject);
    			}
    			json.put("result", jsonArray);
    			json.put("total", pager.getTotal());
    			json.put("pageNo", pager.getPageNo());
    			json.put("pageSize", pager.getPageSize());
    		}
    	}else{
    		json.put("message", "该车友会ID不存在");
    	}
        if (StringUtils.isBlank(callback)) {
        	resp.getWriter().println(json.toString());
    	} else{
    		resp.getWriter().println(EncodeUtils.encodeForHTMLFilterNull(callback) + "(" + json.toString() + ")");
    	}
    }
}
